package qj.tool.db.orientdb;

import qj.tool.db.Key;
import qj.util.funct.F1;

import com.orientechnologies.orient.core.exception.OSerializationException;
import com.orientechnologies.orient.core.id.OClusterPositionFactory;
import com.orientechnologies.orient.core.id.OClusterPositionLong;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.serialization.OSerializableStream;

public class KeyImpl implements Key {
	public static F1<Key, ORID> idF = new F1<Key, ORID>() {public ORID e(Key obj) {
		return ((KeyImpl)obj).identity;
	}};
	public static F1<Key, String> toStringF = new F1<Key, String>() {public String e(Key obj) {
		return KeyImpl.toString(obj);
	}};

	public ORecordId identity;

	public KeyImpl(ORID identity) {
		this.identity = (ORecordId) identity;
	}
	
	public String toString() {
		return identity.toString();
	}
	
	public static String toString(Key key) {
		if (key== null) {
			return null;
		}
		KeyImpl ki = (KeyImpl) key;
		return ki.identity.clusterId + "_" + ki.identity.clusterPosition.longValue();
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((identity == null) ? 0 : identity.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		KeyImpl other = (KeyImpl) obj;
		if (identity == null) {
			if (other.identity != null)
				return false;
		} else if (!identity.equals(other.identity))
			return false;
		return true;
	}

	public static Key fromString(String id) {
		if (id == null) {
			return null;
		}
		String[] split = id.split("_");
		if (split.length != 2) {
			return null;
		}
		return new KeyImpl(new ORecordId(Integer.parseInt(split[0]), OClusterPositionFactory.INSTANCE.valueOf(Long.parseLong(split[1]))));
	}

	public static F1<String, Key> fromStringF = new F1<String, Key>() {public Key e(String keyStr) {
		return fromString(keyStr);
	}};

}
